package com.promise.jokerdream.work.signin

import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.response.pc.QueryBirthdayResponse
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.utils.AppContext

// 生日祝福工作
class BirthdayWork(override val uin: String): BaseWork(uin) {
    
    override val name: String
        get() = "生日祝福"
    
    override val priority: Int
        get() = 9
    
    private val gameApi by lazy { GameApi() }
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询生日信息
            val queryResult = gameApi.queryBirthday()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    processBirthdayResponse(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 处理生日查询响应
     */
    private suspend fun processBirthdayResponse(response: QueryBirthdayResponse): WorkResult {
        // 2. 如果在生日周内，领取专属大礼
        if (response.inEvent == 1 && response.drawFreePresent == 0) {
            val freePresentResult = gameApi.getBirthdayFreePresent()
            freePresentResult.foldWithApiException(
                onSuccess = { presentResponse ->
                    historyManager.addHistory(name, presentResponse.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        }
        
        // 3. 如果收到的祝福值足够，领取祝福大礼
        if (response.receivedWishesNum >= response.wishesRequired && response.drawWishesPresent == 0) {
            val wishesPresentResult = gameApi.getBirthdayWishesPresent()
            wishesPresentResult.foldWithApiException(
                onSuccess = { presentResponse ->
                    historyManager.addHistory(name, presentResponse.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        }

        // 如果好友列表为空，直接结束
        if (response.friends.isEmpty()) {
            return WorkResult.Success
        }
        
        // 4. 循环祝福好友，送完后刷新好友列表，直到祝福失败
        var currentResponse = response
        var shouldContinue = true
        var loopCount = 0
        val maxLoops = 20
        
        while (shouldContinue && currentResponse.friends.isNotEmpty() && loopCount < maxLoops) {
            loopCount++
            for (friend in currentResponse.friends) {
                if (friend.canSendWishes == 1) {
                    val wishResult = gameApi.sendBirthdayWishes(friend.uin)
                    wishResult.foldWithApiException(
                        onSuccess = { wishResponse ->
                            historyManager.addHistory(name, wishResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                            shouldContinue = false // 祝福异常，停止循环
                        }
                    )
                    
                    if (!shouldContinue) break
                }
            }

            if (currentResponse.friends.size < 2) {
                shouldContinue = false // 只有一个好友压根不需要继续刷新了
            }
            
            // 刷新好友列表
            if (shouldContinue) {
                val refreshResult = gameApi.refreshBirthdayFriends()
                refreshResult.foldWithApiException(
                    onSuccess = { refreshResponse ->
                        currentResponse = refreshResponse
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                        shouldContinue = false // 刷新失败，停止循环
                    }
                )
            }
        }
        
        // 5. 重新查询生日信息，检查是否可以领取友好度礼包
        val reQueryResult = gameApi.queryBirthday()
        reQueryResult.foldWithApiException(
            onSuccess = { reResponse ->
                if (reResponse.wishDegree >= reResponse.wishDegreeRequired) {
                    val wishDegreePresentResult = gameApi.getBirthdayWishDegreePresent()
                    wishDegreePresentResult.foldWithApiException(
                        onSuccess = { presentResponse ->
                            historyManager.addHistory(name, presentResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                        }
                    )
                }
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
            }
        )
        
        return WorkResult.Success
    }
}